from django.utils import simplejson

from google.appengine.ext import webapp
from google.appengine.ext.webapp.util import run_wsgi_app

from models import *

class TopicStatsByTopics(webapp.RequestHandler):
	def get(self):
		# split topics parameter
		topicIdsStr = self.request.get('topics').split(',')

		# filter out an invalid topic definition
		topicIds = []

		for topicIdStr in topicIdsStr:
			try:
				topicIds += [int(topicIdStr)]
			except ValueError:
				pass

		# fetch all available topic stat
		topics = TopicStat.listByTopics(topicIds)

		# convert into list/dict
		topicList = [topic.json() for topic in topics]

		if (self.request.get('vcKey') != ''):
			user = NarisaUser.all().filter('vcKey =', self.request.get('vcKey')).fetch(1)

			if (len(user) == 1):
				query = TagHistory.gql('WHERE topicId IN :topicIds AND user = :user',
						topicIds = [topic.topicId for topic in topics],
						user = user[0])
				myTags = query.fetch(len(topics))

				for mine in myTags:
					for topic in topicList:
						if (topic['topicId'] == mine.topicId and topic['tag'] == mine.tag.name):
							topic['mine'] = True

		# convert result into JSON serializable object
		self.response.out.write(simplejson.dumps(topicList))

class TopicStatsByTag(webapp.RequestHandler):
	def get(self):
		# get tag
		tag = Tag.find(self.request.get('tagName'))

		if tag == None:
			return

		# fetch all available topic stat
		topics = TopicStat.listByTag(tag)

		# convert into list/dict
		topicList = [topic.json() for topic in topics]

		# convert result into JSON serializable object
		self.response.out.write(simplejson.dumps(topicList))

application = webapp.WSGIApplication(
		[
				('/topicStats/byTopics', TopicStatsByTopics),
				('/topicStats/byTag', TopicStatsByTag)

		],
		debug=True)

def main():
	run_wsgi_app(application)

if __name__ == "__main__":
	main()

